import { Request, Response } from "express";
import bcrypt from "bcryptjs";
import { query } from "../config/database";
import { User, CreateUserRequest, UpdateUserRequest } from "../model/types";
import {
  successResponse,
  errorResponse,
  paginatedResponse,
} from "../utils/response";

export class UserController {
  // 获取用户列表
  static async getUsers(req: Request, res: Response): Promise<void> {
    try {
      const {
        page = 1,
        pageSize = 20,
        username,
        realName,
        status,
        roleId,
        sortBy = "createdAt",
        sortOrder = "desc",
      } = req.query;

      const offset = (Number(page) - 1) * Number(pageSize);
      let whereConditions = [];
      let params: any[] = [];

      // 构建WHERE条件
      if (username) {
        whereConditions.push("u.username LIKE ?");
        params.push(`%${username}%`);
      }

      if (realName) {
        whereConditions.push("u.real_name LIKE ?");
        params.push(`%${realName}%`);
      }

      if (status) {
        whereConditions.push("u.status = ?");
        params.push(status);
      }

      if (roleId) {
        whereConditions.push("ur.role_id = ?");
        params.push(roleId);
      }

      const whereClause =
        whereConditions.length > 0
          ? `WHERE ${whereConditions.join(" AND ")}`
          : "";

      // 获取总数
      const countQuery = `
        SELECT COUNT(DISTINCT u.id) as total
        FROM users u
        LEFT JOIN user_roles ur ON u.id = ur.user_id
        ${whereClause}
      `;

      const { rows: countRows } = await query(countQuery, params);
      const total = countRows[0].total;
      const totalPages = Math.ceil(total / Number(pageSize));

      // 获取用户列表
      const userQuery = `
        SELECT
          u.id,
          u.username,
          u.email,
          u.phone,
          u.real_name as realName,
          u.avatar,
          u.department,
          u.class_info as classInfo,
          u.status,
          u.created_at as createdAt,
          u.updated_at as updatedAt,
          GROUP_CONCAT(
            JSON_OBJECT(
              'id', r.id,
              'name', r.name
            )
          ) as roles
        FROM users u
        LEFT JOIN user_roles ur ON u.id = ur.user_id
        LEFT JOIN roles r ON ur.role_id = r.id
        ${whereClause}
        GROUP BY u.id
        ORDER BY u.${sortBy} ${sortOrder}
        LIMIT ? OFFSET ?
      `;

      params.push(Number(pageSize), offset);
      const { rows } = await query(userQuery, params);

      // 处理角色数据
      const users = rows.map((user: any) => ({
        ...user,
        roles: user.roles ? JSON.parse(`[${user.roles}]`) : [],
      }));

      paginatedResponse(res, users, {
        page: Number(page),
        pageSize: Number(pageSize),
        total,
        totalPages,
      });
    } catch (error) {
      console.error("获取用户列表失败:", error);
      errorResponse(res, "获取用户列表失败");
    }
  }

  // 根据ID获取用户
  static async getUserById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      const userQuery = `
        SELECT
          u.id,
          u.username,
          u.email,
          u.phone,
          u.real_name as realName,
          u.avatar,
          u.department,
          u.class_info as classInfo,
          u.status,
          u.created_at as createdAt,
          u.updated_at as updatedAt,
          GROUP_CONCAT(
            JSON_OBJECT(
              'id', r.id,
              'name', r.name
            )
          ) as roles
        FROM users u
        LEFT JOIN user_roles ur ON u.id = ur.user_id
        LEFT JOIN roles r ON ur.role_id = r.id
        WHERE u.id = ?
        GROUP BY u.id
      `;

      const { rows } = await query(userQuery, [id]);

      if (rows.length === 0) {
        return errorResponse(res, "用户不存在", 404);
      }

      const user = {
        ...rows[0],
        roles: rows[0].roles ? JSON.parse(`[${rows[0].roles}]`) : [],
      };

      successResponse(res, user);
    } catch (error) {
      console.error("获取用户详情失败:", error);
      errorResponse(res, "获取用户详情失败");
    }
  }

  // 创建用户
  static async createUser(req: Request, res: Response): Promise<void> {
    try {
      const {
        username,
        password,
        email,
        phone,
        realName,
        department,
        classInfo,
        roleIds = [],
      }: CreateUserRequest & { roleIds?: number[] } = req.body;

      // 验证必填字段
      if (!username || !password || !email || !realName) {
        return errorResponse(res, "缺少必填字段");
      }

      // 检查用户名是否已存在
      const { rows: existingUsers } = await query(
        "SELECT id FROM users WHERE username = ? OR email = ?",
        [username, email]
      );

      if (existingUsers.length > 0) {
        return errorResponse(res, "用户名或邮箱已存在");
      }

      // 加密密码
      const saltRounds = 10;
      const hashedPassword = await bcrypt.hash(password, saltRounds);

      // 创建用户
      const insertQuery = `
        INSERT INTO users (
          username, password_hash, email, phone, real_name,
          department, class_info, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'active')
      `;

      const { rows } = await query(insertQuery, [
        username,
        hashedPassword,
        email,
        phone || null,
        realName,
        department || null,
        classInfo || null,
      ]);

      const userId = rows[0].insertId;

      // 分配角色
      if (roleIds.length > 0) {
        const roleValues = roleIds
          .map((roleId) => `(${userId}, ${roleId})`)
          .join(", ");
        await query(
          `INSERT INTO user_roles (user_id, role_id) VALUES ${roleValues}`
        );
      }

      successResponse(res, { id: userId }, "用户创建成功", 201);
    } catch (error) {
      console.error("创建用户失败:", error);
      errorResponse(res, "创建用户失败");
    }
  }

  // 更新用户
  static async updateUser(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const {
        email,
        phone,
        realName,
        department,
        classInfo,
        status,
        roleIds,
      }: UpdateUserRequest & { roleIds?: number[] } = req.body;

      // 检查用户是否存在
      const { rows: existingUsers } = await query(
        "SELECT id FROM users WHERE id = ?",
        [id]
      );

      if (existingUsers.length === 0) {
        return errorResponse(res, "用户不存在", 404);
      }

      // 更新用户信息
      const updateFields = [];
      const params = [];

      if (email !== undefined) {
        updateFields.push("email = ?");
        params.push(email);
      }

      if (phone !== undefined) {
        updateFields.push("phone = ?");
        params.push(phone);
      }

      if (realName !== undefined) {
        updateFields.push("real_name = ?");
        params.push(realName);
      }

      if (department !== undefined) {
        updateFields.push("department = ?");
        params.push(department);
      }

      if (classInfo !== undefined) {
        updateFields.push("class_info = ?");
        params.push(classInfo);
      }

      if (status !== undefined) {
        updateFields.push("status = ?");
        params.push(status);
      }

      if (updateFields.length > 0) {
        const updateQuery = `UPDATE users SET ${updateFields.join(
          ", "
        )} WHERE id = ?`;
        params.push(id);
        await query(updateQuery, params);
      }

      // 更新角色分配
      if (roleIds !== undefined) {
        // 删除现有角色
        await query("DELETE FROM user_roles WHERE user_id = ?", [id]);

        // 添加新角色
        if (roleIds.length > 0) {
          const roleValues = roleIds
            .map((roleId) => `(${id}, ${roleId})`)
            .join(", ");
          await query(
            `INSERT INTO user_roles (user_id, role_id) VALUES ${roleValues}`
          );
        }
      }

      successResponse(res, null, "用户更新成功");
    } catch (error) {
      console.error("更新用户失败:", error);
      errorResponse(res, "更新用户失败");
    }
  }

  // 删除用户
  static async deleteUser(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      // 检查用户是否存在
      const { rows: existingUsers } = await query(
        "SELECT id FROM users WHERE id = ?",
        [id]
      );

      if (existingUsers.length === 0) {
        return errorResponse(res, "用户不存在", 404);
      }

      // 删除用户角色关联
      await query("DELETE FROM user_roles WHERE user_id = ?", [id]);

      // 删除用户
      await query("DELETE FROM users WHERE id = ?", [id]);

      successResponse(res, null, "用户删除成功");
    } catch (error) {
      console.error("删除用户失败:", error);
      errorResponse(res, "删除用户失败");
    }
  }

  // 更新用户状态
  static async updateUserStatus(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const { status } = req.body;

      if (!["active", "inactive", "suspended"].includes(status)) {
        return errorResponse(res, "无效的状态值");
      }

      const { rows } = await query("UPDATE users SET status = ? WHERE id = ?", [
        status,
        id,
      ]);

      if (rows[0].affectedRows === 0) {
        return errorResponse(res, "用户不存在", 404);
      }

      successResponse(res, null, "用户状态更新成功");
    } catch (error) {
      console.error("更新用户状态失败:", error);
      errorResponse(res, "更新用户状态失败");
    }
  }
}
